/**
 * @author 梅峰
 * @class SysManager.Properties
 * 参数数据
 * 
 * Dependence: 
 * 		javascript/SysManager.js
 */
SysManager.Properties = function(){
	var record;	//当前选定行.
	var parentPropertiesId;
	var parentIsProperty = true;
	var pageLimit = 10;
	
	
	var propertiesColumnPanel;
	var cb;
	var propertiesDataStore;	//数据源.Ext.data.Store.
	var propertiesColumn;
	var propertiesToolbar;
	var propertiesGrid;
	var propertiesTree;
	
	
	function createPropertiesDataStore(){
		return new Ext.data.Store({
			proxy : new Ext.data.HttpProxy({
				url : 'properties.action?method=page',
				method:'GET'
			}),
			reader : new Ext.data.JsonReader({
				id : 'id',
				root : 'data',
				totalProperty : 'totalProperty',
				fields : [
					{name : 'id', mapping : 'id'},
					{name : 'businessCode', mapping : 'businessCode'},
					{name : 'name', mapping : 'name'},
					{name : 'type', mapping : 'type'},
					{name : 'status', mapping : 'status'}
				]
			}),
			listeners : {"beforeload" : beforeloadHandler}
		});
	}
	
	function beforeloadHandler(){
		if(parentIsProperty){
			propertiesDataStore.baseParams = {propertyId:record.propertyId};
		}else{
			propertiesDataStore.baseParams = {parentId:parentPropertiesId};
		}
	}
	
	
	function createPropertiesGrid(){
		propertiesDataStore = createPropertiesDataStore();
		return new Ext.grid.GridPanel({
	    	//el : 'properties-grid-div',
	    	//width:Ext.get("content").getWidth(),
	    	height: window.ActiveXObject ? (Ext.get("properties-grid-div").getHeight() * 0.84) : Ext.get("properties-grid-div").getHeight(),
	    	//Ext.get("properties-grid-div").getHeight(),
	    	viewConfig:{forceFit:true},//自动填充列宽.
	    	store : propertiesDataStore,
	    	autoLoad : false,
	    	cm : new Ext.grid.ColumnModel({
				defaultSortable : true,
				columns : [
					new Ext.grid.CheckboxSelectionModel(),
					new Ext.grid.RowNumberer({header:'行号',width:40}),
			        {header: '业务代码', dataIndex: 'businessCode', width: 100},
			        {header: '名称', dataIndex: 'name', width: 100},
			        {header: '所属类型', dataIndex: 'type',width : 100},
			        {header: '状态', dataIndex : 'status', width : 100}
				]
			}),
	    	trackMouseOver : false,
	    	sm : new Ext.grid.CheckboxSelectionModel(),
	    	tbar : new Ext.Toolbar([
		    	{text:'新增参数',icon:'icons/toolBar/add.gif',handler:showPropertiesAddWin}, '-',
		    	{text:'修改参数',icon:'icons/toolBar/plugin.gif',handler:showPropertiesModifyWin}, '-',
		    	{text:'删除参数',icon:'icons/toolBar/delete.gif',handler:showDeletePropertiesWin}
			]),
	    	bbar: new Ext.PagingToolbar({
		            pageSize: pageLimit,
		            store: propertiesDataStore,
		            displayInfo: true,
		            displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
		            emptyMsg: "没有记录"
		        }),
		    listeners : {'rowdblclick' : nextLevelProperties}
	    });
	}
    
	var treeLoader = new Ext.tree.TreeLoader({
		dataUrl : '/properties.action?method=selectByParent',
		createNode : function(attr){
			return new Ext.tree.AsyncTreeNode({
				id : attr.id,
				text : attr.name,
				code : attr.code,
				englishName : attr.englishName,
				type : attr.type || '',
				draggable : false
			});
		},
		processResponse : function(response, node, callback, scope){
			var result = Ext.util.JSON.decode(response.responseText);
			var json = result.data;
			try {
				var o = json;
				node.beginUpdate();
				for(var i = 0, len = o.length; i < len; i++){
					var n = this.createNode(o[i]);
					if(n){
						node.appendChild(n);
					}
				}
				node.endUpdate();
				this.runCallback(callback, scope || node, [node]);
			}catch(e){
				this.handleFailure(response);
			}
		},
		listeners : {
			'beforeload' : function(loader, node){
				if(!node.id){
					return false;
				}
				this.baseParams.type = node.attributes.type;
			}
		}
	});
    
    
    function createPropertiesTree(){
    	return new Ext.tree.TreePanel({
	    	title : '系统参数',
	    	border : true,
	    	columnWidth : 0.2,
			height:Ext.get("properties-grid-div").getHeight(),
			containerScroll : true,
			loader : treeLoader,
			//autoLoad : false,
			rootVisible : false,
			root : new Ext.tree.AsyncTreeNode({text : '系统参数', id : '0'}),
			listeners : {'click' : clickPropertiesType}
		});
    }
        
    
    function createPropertiesColumnPanel(){
    	propertiesTree = createPropertiesTree();
    	propertiesGrid = createPropertiesGrid();
    	return new Ext.Panel({
			border : false,
		    layout:'column',
		    items: [
		    {
		    	border : false,
		        columnWidth: .2,
		        items :[propertiesTree]
		    }
		    ,{
		    	border : false,
		        columnWidth: .8,
		        items :[propertiesGrid]
		    }]
		});
    }
	
    
	function selectProperties(node, e){
		propertiesDataStore.load({params:{'start':0,'limit':pageLimit,'parentId':node.attributes.id}});
	}
	
	
 	/**
 	 * 显示下一级参数.
 	 */   
    function nextLevelProperties(grid, rowIndex, columnIndex, e){
	    setNextProperties(grid.getStore().getAt(rowIndex).get("id"));
	};
	
	
	/**
	 * 点击左侧<参数>tree Handler.
	 */
	function clickPropertiesType(node){
		if(node.attributes.type == ''){
			setNextProperties(node.id);
		}else if(record && record.propertyId){
			parentIsProperty = true;
			propertiesDataStore.load({params:{'start':0,'limit':pageLimit,'propertyId':record.propertyId}});
		}
	}
	
	//private	选中<参数>后进行必要的设置.
	function setNextProperties(propertiesId){
		parentIsProperty = false;	//当前选中的是<参数>,不是<参数类型>,指要进行多层参数的维护.
		parentPropertiesId = propertiesId;	//当前操作的<参数>.
		propertiesDataStore.load({params:{'start':0,'limit':pageLimit,'parentId':propertiesId}});
	}
	
	
	/**
	 * 得到选中的参数.
	 */
	function getSelectProperties(){
		var propertiesList = propertiesGrid.getSelectionModel().getSelections();
		var idsList = [];
		if(propertiesList.length == 0){
			Ext.Msg.alert('提示','请选择项目进行操作!');
		}else{
			for(var i=0; i<propertiesList.length; i++){
	    		idsList.push(propertiesList[i].get('id'));
	    	}
		}//
		return idsList;
	};
	
	
	/**
	 * 打开添加页面.
	 */
	function showPropertiesAddWin(){
		SysManager.Properties.Form.showForm();
	};
	
	
	/**
	 * 修改参数
	 */
	function showPropertiesModifyWin(){
		var idsList = getSelectProperties();
		var num = idsList.length;
		if(num > 1){
			Ext.MessageBox.alert('提示','只能选择一条项目进行修改!')
		}else if(num == 1){
			var id = idsList[0];
			SysManager.Properties.Form.showForm(id);
		}
	};
	
	
	/**
	 * 打开删除提示.
	 */
	function showDeletePropertiesWin(){
		var idsList = getSelectProperties();
		if(idsList && idsList.length > 0){
			Ext.MessageBox.confirm('提示','您确定要删除选定的参数吗?',
	    		function(btnId){
	    			if(btnId == 'yes'){
	    				deletePropertiesWin(idsList);
	    			}
	    		}
	    	);
		}else{
			Ext.Msg.alert('提示','请选择删除的项目!');
		}
	};
	
	
	/**
	 * 删除参数.
	 * @param {} propertiesId
	 */
	function deletePropertiesWin(propertiesId){
		var msgTip = Ext.MessageBox.show({
	           msg: '正在删除所选项目, 稍后...',
	           progressText: '删除...',
	           width:300,
	           wait:true,
	           waitConfig: {interval:200}
		});
	    	
	    Ext.Ajax.request({
	    	url : 'properties.action?method=del',
	    	params : {ids:propertiesId},
	    	method : 'POST',
	    	success : function(response, options){
	    		msgTip.hide();
	    		var result = Ext.util.JSON.decode(response.responseText);
	    		if(result.success){
	    			//成功
	    			for(var i=0; i < propertiesId.length; i++){
	    				var index = propertiesDataStore.find('id',propertiesId[i]);
		    			if(index != -1){
		    				var rec = propertiesDataStore.getAt(index);
		    				propertiesDataStore.remove(rec);
		    			}
	    			}
	    			Ext.Msg.alert('提示','成功删除项目');
	    		}else{
	    			Ext.Msg.alert('提示','该参数类别不能删除，因为含有子项.');
	    		}
	    	},
	    	failure : function(response, options){
	    		msgTip.hide();
	    		Ext.Msg.alert('提示','删除失败.');
	    	}
	    });
	};
	
	
	
	return {
		/**
		 * 初始化.
		 * @param divName 渲染表格的位置.
		 */
		initialize : function(divName, limit){
			this.pageLimit = limit;
			propertiesColumnPanel = createPropertiesColumnPanel();
			propertiesColumnPanel.render(divName);
		},
		
		/**
		 * 显示给定<参数类型>的参数列表.
		 */
		showProperties : function (propertyId, name, code, enName){
			propertiesTree.getRootNode().eachChild(function(node){
				propertiesTree.getRootNode().removeChild(node);
			});
			
			propertiesTree.getRootNode().appendChild(
				new Ext.tree.AsyncTreeNode({
					id : propertyId,
					text : name,
					code : code,
					englishName : enName,
					type : 'p',//有则证明是property.
					draggable : false
				})
			);
			
			record = new SysManager.Property.Record(propertyId,name,code,enName);
		   	propertiesDataStore.load({params:{'start':0,'limit':pageLimit,'propertyId':record.propertyId}});
		},
		
		
		/**
		 * 用选定的<参数类型>信息填充form.
		 * @param propertiesForm 被填充form.
		 */
		initPropertiesForm : function(propertiesForm){
			if(record){
				//设置form中的值.
				if(parentIsProperty){//第一层.
					propertiesForm.getForm().setValues({
					"propertyName":record.propertyName,
					"propertyId":record.propertyId,
					"propertyCode":record.propertyCode,
					"englishName":record.propertyCode});
				}else{//参数多层.
					propertiesForm.getForm().setValues({
					"propertyName":record.propertyName,
					"propertyCode":record.propertyCode,
					"englishName":record.propertyEnglishName,
					"parentId":parentPropertiesId});
				}
				return true;
			}else{
				return false;
			}
		},
		
		gridReload : function(){
			propertiesDataStore.reload();
		}
		
	};
	

}();
